package com.atguigu.gmall.list.receiver;

import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.list.service.SearchService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ListReceiver {

    @Autowired
    private SearchService searchService;

    //  上架操作：
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_GOODS_UPPER,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_GOODS),
            key = {MqConst.ROUTING_GOODS_UPPER}
    ))
    public void upperGoods(Long skuId, Message message, Channel channel){
        try {
            //  判断
            if(skuId!=null){
                //  调用上架方法.
                searchService.upperGoods(skuId);
            }
        } catch (Exception e) {
            e.printStackTrace();

            //  第三个表示是否重回队列.
            //  如果你要重回队列的话，那么必须要限定重回的次数;
            /*
            如何处理消费失败的消息?
            if(count>3){
             直接将有消息信息，放入记录表中.  insert into goods_msg(skuId,,,);
            }else{
              channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
            }
            //  日志： log  通过人员查看：为什么失败了.
            */
        }
        //  开启手动确认模式.  如果不确认的话， 那么这条消息会一直在队列中不出队列.
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

    //  下架操作.
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_GOODS_LOWER,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_GOODS),
            key = {MqConst.ROUTING_GOODS_LOWER}
    ))
    public void lowGoods(Long skuId, Message message, Channel channel){
        try {
            //  判断
            if(skuId!=null){
                //  调用上架方法.
                searchService.lowerGoods(skuId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //  开启手动确认模式.  如果不确认的话， 那么这条消息会一直在队列中不出队列.
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
}
